package eclipse.lib.scripting;
import javax.script.*;
import java.io.*;
import java.net.*;
import eclipse.*;
import eclipse.resources.*;
public class JScript {
	private static ScriptEngineManager mgr 		= new ScriptEngineManager();
	private static ScriptEngine jsEngine 		= mgr.getEngineByName("JavaScript");
	private static Invocable invocableEngine 	= (Invocable) jsEngine;
	
	/**
	 * Creates an object in the Scripting engine
	 * @param alias Name of the object
	 * @param obj The Object that is added
	 */
	public static void makeObject(String alias, Object obj)
	{
		jsEngine.put(alias, obj);		
	}
	
	/**
	 * Executes code from the Scripting engine
	 * @param name Name of the script
	 */
	public static Object run(String name)
	{
		try
		{
			return jsEngine.eval(name);
		}
		catch(Exception e)
		{
			ErrorManager.handleError(e);
		}		
		return null;
	}
	/**
	 * Evaluates a script
	 * @param name Name of the function
	 * @param args Arguments of the function
	 */
	public static Object evaluate(String name, Object... args)
	{
		try
		{
			return invocableEngine.invokeFunction(name, args);
		}
		catch(Exception e)
		{
			ErrorManager.handleError(e);
		}		
		return null;
	}
	/**
	 * Adds a Script from the jar
	 * @param Script Script to add
	 */
	public static void addScriptFromJar(String Script)
	{
		importScript(ResourceManager.getInputStream(Script));
		
	}
	/**
	 * Adds a script from a Stream
	 * @param script Script to add
	 */
	public static void importScript(InputStream script)
	{
		try
		{
			InputStreamReader IS = new InputStreamReader(script);
			jsEngine.eval(IS);
		}
		catch(Exception e)
		{
			ErrorManager.handleError(e);
		}
	}
	/**
	 * Adds a script from a URL
	 * @param script Script to add
	 */
	public static void addScriptFromURL(URL script)
	{		
		try
		{
			importScript(script.openStream());
		}
		catch(Exception e)
		{
			ErrorManager.handleError(e);
		}		
	}
	/**
	 * Adds a script from a String path
	 * @param script Script to add
	 */
	public static void addScriptFromPath(String script)
	{
		script = "Scripts/" + script;
		try 
		{
			Reader reader = new FileReader(script);
		    jsEngine.eval(reader);
		} 
		catch(Exception e) 
		{
			ErrorManager.handleError(e);
		}	
	}
	/**
	 * Adds a procedure to the engine	 
	 * @param Procedure Procedure to add as a String
	 */
	public static void addProcedure(String Procedure)
	{
		try
		{
			jsEngine.eval(Procedure);
		}
		catch(Exception e)
		{
			ErrorManager.handleError(e);
		}
	}
}
